package com.atguigu.flink.chapter06.state.keyed;

import com.atguigu.flink.bean.WaterSensor;
import com.atguigu.flink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2023/6/20 14:23
 */
public class ReduceStateDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // 输出每个传感器水位和
        
        env
            .socketTextStream("hadoop162", 8888)
            .map(new WaterSensorMapFunction())
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
    
    
                private ReducingState<WaterSensor> vcSumState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    vcSumState = getRuntimeContext()
                        .getReducingState(
                            new ReducingStateDescriptor<WaterSensor>(
                                "vcSum",
                                new ReduceFunction<WaterSensor>() {
                                    @Override
                                    public WaterSensor reduce(WaterSensor value1,
                                                              WaterSensor value2) throws Exception {
                                        value1.setVc(value1.getVc() + value2.getVc());
                                        return value1;
                                    }
                                },
                                WaterSensor.class
                            )
                        );
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    
                    vcSumState.add(value);
                    
                    out.collect(ctx.getCurrentKey() + " 的水位和: " + vcSumState.get().getVc());
                    
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
 vcSumState.add(value) 添加元素
 vcSumState.get() 获取状态中的值: 聚合后的最终结果
 */